<?php

namespace App\HttpController\Api;

use App\Libs\ClassArr;
use App\Libs\Upload\Image;
use App\Libs\Upload\Video;
use EasySwoole\Http\AbstractInterface\Controller;

class Upload extends Controller
{
    public function index()
    {

    }

    public function file()
    {
        $request = $this->request();
        $files = $request->getSwooleRequest()->files;
        $types = array_keys($files);
        $type = $types[0];
        if (empty($type)) {
            return $this->writeJson(400, [], '上传文件不合法');
        }
        try {
            $classObj = new ClassArr();
            $classStats = $classObj->uploadClassStat();
            $uploadObj = $classObj->initClass($type, $classStats, [$request, $type]);
            if (!$uploadObj) {
                return $this->writeJson(400, [], '上传文件不合法');
            }
            $file = $uploadObj->upload();
        } catch (\Exception $e) {
            return $this->writeJson(400, [], $e->getMessage());
        }

        if (empty($file)) {
            return $this->writeJson(400, [], '上传失败');
        }

        $data = [
            'url' => $file
        ];
        return $this->writeJson(200, $data, 'ok');
    }
}